package impl;

import java.math.BigDecimal;

import java.util.Date;
import java.util.List;

import api.IWallet;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.Lindenmovement;
import entities.Lindenmovementstype;
import entities.Userprofile;

/**
 * Session Bean implementation class Wallet
 */
@Stateless(name = "IWallet")
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public class Wallet implements IWallet {
	@PersistenceContext(unitName = "PhaseBookPU")
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public Wallet() {

	}

	@Override
	public boolean reloadLinden(int uid, int amount) {
		System.out.println("*** WALLET ***");
		System.out.println("*** New User linden euros reload ***");

		// Update profile value
		Userprofile userProfile = em.find(Userprofile.class, uid);
		userProfile.setLindenEuros(userProfile.getLindenEuros().add(
				new BigDecimal(amount)));
		em.persist(userProfile);

		// Add new user movement
		Lindenmovement userMovements = new Lindenmovement();
		userMovements.setUserprofile(userProfile);
		userMovements.setLindenEuros(new BigDecimal(amount));
		userMovements.setLindenmovementstype((Lindenmovementstype) em.find(
				Lindenmovementstype.class, MovementsType.RELOAD.ordinal()));
		userMovements.setDate(new Date());
		em.persist(userMovements);

		return true;

	}

	@Override
	public List<Lindenmovement> getMovements(int uid) {
		System.out.println("*** WALLET ***");
		System.out.println("*** Get User mevements ***");

		Query query = em.createNamedQuery("getLindenMovements");
		query.setParameter("userId", uid);
		return query.getResultList();

	}

}
